from django.conf import settings
from django.http import HttpResponse, HttpRequest
from django.shortcuts import render_to_response
from django.utils.translation import ugettext as _
from google.appengine.api import users
from google.appengine.ext import db
from looptube.models import Playlist, VideoInfo, UserLoopedVideo
from . import commonInit

def init(request, isWidget=True):
    if (not isWidget):
        # init from commonInit()
        resp = commonInit(request)
        if (HttpResponse == resp.__class__):
            return resp     # commonInit() returned HttpResponse
        contextDict = resp  # commonInit() returned dict
    else:
        contextDict = {}            
        contextDict['widget'] = True

    siteHostname = request.get_host();
    contextDict['siteHostname'] = siteHostname
    contextDict['siteName'] = settings.SITE_NAME

    if (siteHostname.startswith('localhost')):
        contextDict['firebugEnabled'] = settings.FIREBUG_ENABLED
        
    return contextDict

# actions

def playlistAction(request, key, widgetType='thin'):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    autoPlay = False
    if (request.GET.__contains__('autoplay') and request.GET['autoplay']):
        autoPlay = True
    try:
        playlist = Playlist.get(key);
    except db.KindError:
        playlist = None
    if (None == playlist):
        videoIDs = ''
        title = ''
    else:
        videoIDs = playlist.getVideoIDs()
        title = playlist.title
        # do not add counter
        #db.run_in_transaction(playlist.increaseCount)
    contextDict['videoIDs'] = videoIDs;
    videoIDList = videoIDs.split(',')
    videoList = []
    for videoID in videoIDList:
        videoInfo = VideoInfo.getVideoInfo('youtube', videoID, True)
        if (videoInfo):
            videoList.append(videoInfo)
    contextDict['videoList'] = videoList
    contextDict['isPlaylist'] = True

    contextDict['playlistKey'] = key
    contextDict['pageTitle'] = title

    if ('thin' == widgetType):
        contextDict['widgetTypeName'] = 'widgetContent'
        contextDict['playerWidth'] = 160
        contextDict['playerHeight'] = 140
    else:
        contextDict['widgetTypeName'] = 'wideWidgetContent'
        contextDict['playerWidth'] = 320
        contextDict['playerHeight'] = 260
        
    if (autoPlay):
        contextDict['nowPlayingInitMsg'] = _('Please wait ...')
    else:
        contextDict['nowPlayingInitMsg'] = _('Please click Play button!')
        
    return render_to_response('widget/playlist.html', contextDict)

def highlightVideosAction(request):
    #init from init()
    resp = init(request, isWidget=False)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (request.GET.__contains__('videos')):
        highlightVideos = request.GET['videos']
    else:
        highlightVideos = '';
    
    hlvideoIDList = highlightVideos.split(',')
    hlvideoList = []
    for videoID in hlvideoIDList:
        if ('' == videoID):
            continue
        videoInfo = VideoInfo.getVideoInfo('youtube', videoID, True)
        if (videoInfo):
            hlvideoList.append(videoInfo)
            
    contextDict['hlvideoList'] = hlvideoList
    contextDict['highlightVideos'] = highlightVideos
    return render_to_response('sidebar/highlightvideos.html', contextDict)

def addUserRecentLoopedVideosAction(request):
    #init from init()
    resp = init(request, isWidget=False)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    user = users.get_current_user()
    if (user):
        userEmail = user.email()
    else:
        userEmail = 'wangpy.tw@gmail.com'
        
    embedCode = ( ('<iframe height="265" frameborder="0" width="200" scrolling="no"'
                   + ' src="http://%s/widget/urlv?user=%s"></iframe>') 
                  % (contextDict['siteHostname'], userEmail))
    contextDict['embedCode'] = embedCode
    
    contextDict['pageTitle'] = _('Embed user recently looped videos widget')
    
    return render_to_response('adduserrecentloopedvideos.html', contextDict)

def addPlaylistWidgetAction(request, key):
    #init from init()
    resp = init(request, isWidget=False)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    playlist = Playlist.get(key);
    if (None == playlist):
        return HttpResponseRedirect('/')
    else:
        videoIDs = playlist.videoIDs
        title = playlist.title

    embedCode = ( ('<iframe height="350" frameborder="0" width="200" scrolling="no"'
                   + ' src="http://%s/widget/playlist/%s"></iframe>') 
                  % (contextDict['siteHostname'], key))
    wideEmbedCode = ( ('<iframe height="305" frameborder="0" width="520" scrolling="no"'
                   + ' src="http://%s/widget/wideplaylist/%s"></iframe>') 
                  % (contextDict['siteHostname'], key))
    contextDict['embedCode'] = embedCode
    contextDict['wideEmbedCode'] = wideEmbedCode
    
    contextDict['pageTitle'] = _('Embed Playlist Widget')+': '+playlist.title
    
    return render_to_response('addplaylistwidget.html', contextDict)
    
def userRecentLoopedVideosAction(request):
    #init from init()
    resp = init(request)
    if (HttpResponse == resp.__class__):
        return resp     # init() returned HttpReponse
    contextDict = resp  # init() returned dict

    if (request.GET.__contains__('limit')):
        limit = request.GET['limit']
        if (limit > 20):
            limit = 20
    else:
        limit = 10

    if (not request.GET.__contains__('user')):
        user = None
    else:
        try:
            user = users.User(request.GET['user'])
            userRecentLoopedVideos = UserLoopedVideo.getUserRecentLoopedVideos(user, limit)
        except:
            user = None

    if (user):
        contextDict['user'] = user
        contextDict['userRecentLoopedVideos'] = userRecentLoopedVideos
    
    return render_to_response('widget/userrecentloopedvideos.html', contextDict)
